#!/usr/bin/env python2
# -*- coding: utf-8 -*-

import subprocess, time, os, sys

cmf = "./cmf"
iterations = 1000

def instanceFromFile(path):
	f = open(path)
	input = ""
	for line in f:
		input += line
	return input.strip()

def getTestFiles(folder, ext):
	testFiles = []
	for root, dirs, files in os.walk(folder):
		for file in files:
			if file.endswith(ext):
				testFiles.append(os.path.join(root, file)[:-3])
	return testFiles

def launch(input):
	command = [cmf]
	subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
	stdout = subp.communicate(input=input)[0]
	return stdout.strip()

def testSerie(dir):

	hits = 0
	miss = 0
	maxdiff = 0

	inputFiles = getTestFiles("./" + dir, ".in")
	inputFiles.sort()

	for i in range(len(inputFiles)):
		input = instanceFromFile(inputFiles[i] + ".in")
		output = launch(input)
		predicted = instanceFromFile(inputFiles[i] + ".out")

		maxdiff = max(maxdiff, abs(int(output.split()[0]) - int(predicted.split()[0])))

		if(output.split()[0] == predicted.split()[0]):
			hits += 1
			print inputFiles[i] + " aprobado!"
		else:
			miss += 1
			print inputFiles[i] + " falló!"

			print "\toutput > " + output
			print "\tpredicted > " + predicted

	print str(hits) + " hits / " + str(miss) + " miss / max-diff: " + str(maxdiff)

def testTimeSerie(dir):

	inputFiles = getTestFiles("./" + dir, ".in")
	inputFiles.sort()

	for i in range(len(inputFiles)):

		totalTime = 0

		for j in range(iterations):
			input = instanceFromFile(inputFiles[i] + ".in")
			output = launch(input)
			totalTime += int(output)

		totalTime = totalTime / iterations
		print inputFiles[i] + "\t" + str(totalTime)

#testSerie("SerieA1")
#testSerie("SerieA2")
#testSerie("SerieB")

testTimeSerie("SerieA1")
testTimeSerie("SerieA2")
testTimeSerie("SerieB")